<?php

class BlgMetadata extends BlgData{
	
	protected function initializeAttributes() {
		parent::initializeAttributes();		
		$this->attributes['type']= "metadata";
		
		$this->attributes['id']= 			NULL;
		$this->attributes['entity_guid']= 	NULL;
		$this->attributes['name']= 			NULL;
		$this->attributes['value']= 		NULL;
		$this->attributes['name_id']= 		NULL;
		$this->attributes['value_id']= 		NULL;		
		$this->attributes['value_type']= 	NULL;
		$this->attributes['owner_guid']= 	NULL;
		$this->attributes['access_id']= 	ACCESS_PRIVATE;
		$this->attributes['time_created']= 	NULL;
		$this->attributes['enabled']= 		'yes';
		
		$this->exists= FALSE;
	}
	
	function __construct($id_or_guid, $type_or_name=NULL){
		$this->initializeAttributes();				
		$this->load($id_or_guid, $type_or_name);
	}
	
	protected function load($id_or_guid, $type_or_name=NULL){
		if(NULL===$type_or_name){
			$metadata= blg_metadata_get($id_or_guid);			
		}else{
			$metadata= blg_metadata_get_entity($id_or_guid, $type_or_name);	
		}
		
		if(FALSE!==$metadata){
			$this->exists= TRUE;
			$this->attributes= array_merge($this->attributes, $metadata);
			return TRUE;
		}

		return FALSE;
	}
	
	protected function reload(){
		if(!empty($this->attributes['id'])){
			return $this->load($this->attributes['id']);
		}
		return FALSE;
	}
	
	/* METHODS */
	
	public function set_value($value, $value_type=NULL){
		$result= blg_metadata_update_value($this->attributes['id'], $value, $value_type);
		$this->reload();
		return $result;
	}
	
	public function set_access($access_id){
		$return= blg_metadata_update_acess($this->attributes['id'], $access_id);
		$this->reload();
		return $result;
	}
	
	public function get_value(){
		if($this->attributes['value_type']=='string')
			return (string) $this->attributes['value'];
		else if($this->attributes['value_type']=='integer')
			return (int) $this->attributes['value'];
	}
	
	/***********************************************************
	 * 						NOT ABSTRACT
	 ***********************************************************/	
	public function getURL(){}
	public function save(){}
	public function delete(){}	
	
	/* STATIC */
	
	/**
	 * Create new metadata
	 * @param int $entity_guid
	 * @param string $name
	 * @param string $value
	 * @param string $value_type
	 * @param int $owner_guid
	 * @param int $access_id
	 * @param int $time_created
	 * @return BlgMetadata|FALSE
	 */
	public static function create($entity_guid, $name, $value, $value_type=NULL, $owner_guid=NULL, $access_id=ACCESS_DEFAULT, $time_created= NULL){
		if(FALSE===blg_metadata_exists($entity_guid, $name)){
			$metadata_id= blg_metadata_add($entity_guid, $name, $value, $value_type, $owner_guid, $access_id, $time_created);
			if(FALSE!==$metadata_id)
				return new BlgMetadata($metadata_id);
		}
			
		return FALSE;
	}
}